/**
 * 
 */
package org.vsg.stock.dzh;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.vsg.common.configration.PropertiesSupport;
import org.vsg.stock.basic.persistence.StockInfoDao;


/**
 * @author vison
 *
 */
public class GenerateDailyLine {

	private final static Logger logger = LoggerFactory.getLogger(GenerateDailyLine.class);	
	
	static private DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
	
	private File dzh2Txt;

	private String encoding;

	
	public void exec(ApplicationContext appContext , Date date) throws Exception {
		
		PropertiesSupport proSupport = (PropertiesSupport)appContext.getBean("propertyConfigurer");
		
		String propDailyLine = proSupport.getProperties().getProperty("stock.dailyline.dir");
		if (propDailyLine == null) {
			//logger.warn("Property 'stock.dailyline.dirk' is not defined! ");
			throw new Exception("Property 'stock.dailyline.dir' is not defined!");
		}
		File dailLineDir = new File(propDailyLine);

		String dzh2txtStr = proSupport.getProperties().getProperty("dzh2txt");
		if (dzh2txtStr == null) {
			//logger.warn("Property 'stock.dailyline.dirk' is not defined! ");
			throw new Exception("Property 'dzh2txt' is not defined!");
		}
		dzh2Txt = new File(dzh2txtStr);
		
		encoding = proSupport.getProperties().getProperty("file.encoding");
		
		// --- set the daily handle ---
		String dateStr = format.format(date);
		File dailyFilePath = new File(dailLineDir , dateStr +".txt");
		
		StockInfoDao stockInfoDao = (StockInfoDao)appContext.getBean("stockInfoDao");			
		// --- reade the content ---
		List<String> allStkCodes = stockInfoDao.findAllCode();

		List<String> lines = null;
		
		List<String> contentLines = new ArrayList<String>();
		
		String stkCode = null;
		
		for (Iterator<String> allStockCodesIter = allStkCodes.iterator() ; allStockCodesIter.hasNext();) {
			stkCode = allStockCodesIter.next();
			
			lines = hqExecCommand(stkCode);
			Collections.reverse( lines );
			for (int i = 0 ; i < lines.size() ; i++) {
				String line = lines.get(i);
				if (line.indexOf( dateStr ) != -1) {
					line = DataConverter.convert(lines, i, line);
					contentLines.add(line);
					break;
				}
			}
			lines.clear();
			lines = null;
			
			logger.debug( "gen stock daily \""+stkCode+"\" , ok! " );

		}

		OutputStream os = null;
		String lineEnding = "\n";		
		try {
			os = new BufferedOutputStream( new FileOutputStream( dailyFilePath) ); 
			IOUtils.writeLines(contentLines, lineEnding , os);			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		
		} finally {
			
			if (os != null) {
				
				try {
					os.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
			
		}	


	}
	
	private List<String> hqExecCommand(String stockCode) {
		
		Runtime runtime = Runtime.getRuntime();
		
		StringBuffer cmd = new StringBuffer( dzh2Txt.getAbsolutePath() );
		cmd.append(" ");
		cmd.append("getdata ").append("hqfq ");
		cmd.append(stockCode);

		List<String> list = new ArrayList();
		InputStream is = null;
		try {
			Process proc = runtime.exec(cmd.toString());
			
			is = proc.getInputStream();
			// using buffer inputstream 
			InputStreamReader reader = new InputStreamReader(is, encoding);
			BufferedReader breader = new BufferedReader(reader);
			String line =breader.readLine();
			 while (line != null) {
			  	// --- parse object---
			    list.add(line);
			    line = breader.readLine();
			  }
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					is = null;
				}
			}
		}
	        
	     return list;
	}

	

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Calendar cale = Calendar.getInstance();

		// --- get the from date and to date ---
		Date date = cale.getTime();		
		for (String arg : args) {
			if (arg.startsWith("-DrefDate=")) {
				String dateString = arg.replaceFirst("-DrefDate=", "").trim();
				try {
					date = format.parse( dateString );
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}

		}		
		
		ClassLoader clsLoader = GenerateDailyLine.class.getClassLoader();
		// --- run the main page ---
		// build the read the path , dzh's home path
		String[] configContextFiles = {
				"classpath:/spring/configurationContext.xml",
				"classpath*:/spring/applicationContext.xml",
				"classpath*:/spring/dataAccessContext.xml"
		};
		
		ApplicationContext ctx = new ClassPathXmlApplicationContext(configContextFiles,true);
		
	
		GenerateDailyLine mainProg = new GenerateDailyLine();
		
		try {
			mainProg.exec(ctx , date);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		logger.info("program run ... Ok!");
		



	}

}
